package com.gin.kotlin.no_gay_alliance.provider.ngaphp

import android.util.Log
import com.gin.kotlin.no_gay_alliance.R
import com.gin.kotlin.no_gay_alliance.app.App
import com.gin.kotlin.no_gay_alliance.callback.RCallback
import com.gin.kotlin.no_gay_alliance.database.entity.NoticeMsg
import com.gin.nga.callback.NgaCallback
import com.gin.nga.main.NgaApi
import com.gin.nga.response.base.NgaResponse
import com.gin.nga.response.base.SingleData
import com.gin.nga.response.notice.NoticeData
import retrofit2.Call
import retrofit2.Response
import java.lang.ref.WeakReference

class NoticeProvider private constructor() {
    private val TAG = this::class.java.simpleName
    fun enqueue(
        userId: Long = App.INSTANCE.account.userId,
        username: String = App.INSTANCE.account.username,
        api: NgaApi = App.INSTANCE.ngaApi,
        callback: RCallback<List<NoticeMsg>, Nothing>
    ) {
        if (userId == 0L) {
            Log.w(TAG, "当前未登录账号")
            return
        }
        Log.d(TAG, "检查提醒消息, $username($userId)")
        api.noticeApi.list().enqueue(object : NgaCallback<SingleData<NoticeData>> {
            override fun onSuccess(
                call: Call<NgaResponse<SingleData<NoticeData>>>,
                response: Response<NgaResponse<SingleData<NoticeData>>>,
                body: NgaResponse<SingleData<NoticeData>>?,
                data: SingleData<NoticeData>?
            ) {
                val noticeData = body?.data?.data
                if (noticeData != null) {
                    // 将获取到的提醒消息合并为单个列表
                    val res = mutableListOf<NoticeMsg>()
                    noticeData.group0?.map { NoticeMsg(it, userId) }?.forEach { res.add(it) }
                    noticeData.group1?.map { NoticeMsg(it, userId) }?.forEach { res.add(it) }
                    noticeData.group2?.map { NoticeMsg(it, userId) }?.forEach { res.add(it) }
                    noticeData.group3?.map { NoticeMsg(it, userId) }?.forEach { res.add(it) }
                    noticeData.group4?.map { NoticeMsg(it, userId) }?.forEach { res.add(it) }
                    val dao = App.INSTANCE.database.noticeMsgDao()

                    dao.add(res)
                    // 当前所有提醒
                    val list = dao.list(userId).sortedBy { it.time }.reversed()
                    Log.d(TAG, "获取提醒消息成功, $username($userId), 未读: ${list.count { it.unread }}")
                    callback.onSuccess(list, true)
                }
            }

            override fun onError(
                call: Call<NgaResponse<SingleData<NoticeData>>>,
                response: Response<NgaResponse<SingleData<NoticeData>>>,
                body: NgaResponse<SingleData<NoticeData>>?, errorMessage: String
            ) {
                if (response.code() != 200) callback.onError(errorMessage) else {
                    val dao = App.INSTANCE.database.noticeMsgDao()
                    val list = dao.list(userId).sortedBy { it.time }.reversed()
                    if (list.isEmpty())
                        callback.onError(App.INSTANCE.getString(R.string.message_notice_empty))
                    else
                        callback.onSuccess(list, true)
                }
            }
        })
    }

    companion object {
        private var instance: WeakReference<NoticeProvider> = WeakReference(NoticeProvider())
        fun getInstance(): NoticeProvider = instance.get() ?: NoticeProvider().also { instance = WeakReference(it) }
    }
}